#!/bin/bash

host_name=$(hostname)
cur_time=$(date "+%Y-%m-%d %H:%M:%S")

function get_cpu(){
    while IFS=, read -r cpu used idle ;
    do
        sql="insert into monitor.cpu(hostname,date,cpu_core,cpu_used,cpu_free) values('$host_name','$cur_time','$cpu','$used','$idle')"
        sql_insert "$sql"
    done < <( mpstat -P ALL|awk ' NR>4{printf"cpu%d,%.2f%%,%.2f%%\n",$2,100-$12,$12}' )
}

function get_mem(){
    IFS=, read -r used free total used_percent <<< $(free -m|awk 'NR==2{printf"%d,%d,%d,%.2f%%\n",$3,$4,$2,$3/$2*100}')
    sql="insert into monitor.mem(hostname,date,used,free,total,used_percent) values('$host_name','$cur_time','$used','$free','$total','$used_percent')"
    sql_insert "$sql"
}

function get_disk(){
    while IFS=, read -r f_type used free total used_percent mountpoint ;do

        if [ "$f_type" != "tmpfs" ];then
   
            sql="insert into monitor.disk(hostname,date,f_type,used,free,total,used_percent,mountpoint) values('$host_name','$cur_time','$f_type','$used','$free','$total','$used_percent','$mountpoint')"
            sql_insert "$sql"

        fi
    
    done < <(df -Tm| awk 'NR>1{printf"%s,%d,%d,%d,%s,%s\n",$2,$4,$5,$3,$6,$7 }')
}


function sql_insert(){

    sql=$1
    mysql -uam123 -p123456 -h 192.168.88.131 -e "$sql" &>/dev/null

}


function main(){

    get_cpu
    get_mem
    get_disk

}

main




